<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container >
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="营销生产计划单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="planCode">
              <a-input v-model="model.planCode" placeholder="请输入营销生产计划单号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowFlag">
              <j-dict-select-tag type="list" v-model="model.flowFlag" :disabled="formDisabled"dictCode="plan_flow_flag" placeholder="请选择审批流程" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" style="margin-top:10px;margin-bottom: 10px">
            <j-vxe-table
              keep-source
              :ref="refKeys[1]"
              :loading="crmProductionPlanDetailTable.loading"
              :columns="crmProductionPlanDetailTable.columns"
              :dataSource="crmProductionPlanDetailTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="false"
              :toolbar-config="{ btn: [] }"
              :toolbar="!formDisabled"
            >
              <template #toolbarPrefix>  <!-- 覆盖整个工具栏 -->
                <a-space>
                  <a-button type="primary" @click="handleComplete">齐套分析</a-button>
                </a-space>
              </template>
              <template v-slot:planQuantity="{ row }">
                <a-input-number :disabled="formDisabled" style="width:100%" v-model="row.planQuantity" @change="planQuantityInput(row)" :default-value="0" />
              </template>
            </j-vxe-table>
          </a-col>

          <a-col :span="24" >
            <a-form-model-item label="特殊说明" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="description">
              <a-textarea v-model="model.description" rows="4" :disabled="formDisabled" placeholder="请输入特殊说明" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="附件" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="crmProductionPlanFileTable.loading"
          :columns="crmProductionPlanFileTable.columns"
          :dataSource="crmProductionPlanFileTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          >
        <template v-slot:action="{ row }">
          <a @click="handlePreviewReviewDesFiles(row)">预览</a>
        </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import {getAction, postAction} from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
import {
  getRefPromise,
  VALIDATE_FAILED,
  validateFormModelAndTables
} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import {FilePreview} from "@/utils/tslCommon";

  export default {
    name: 'CrmProductionPlanForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          flowFlag:1,
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        validatorRules: {
          flowFlag: [{ required: true, message: '请选择审批流程!' }],
        },
        refKeys: ['crmProductionPlanFile', 'crmProductionPlanDetail', ],
        tableKeys:['crmProductionPlanFile', 'crmProductionPlanDetail', ],
        activeKey: 'crmProductionPlanFile',
        // 生产计划单附件
        crmProductionPlanFileTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '附件',
              key: 'files',
              type: JVXETypes.file,
              token:true,
              responseName:"message",
              placeholder: '请选择文件',
              defaultValue:'',
            },
            {
              title: '操作',
              key: 'action',
              type: JVXETypes.slot,
              fixed: 'right',
              minWidth: '100px',
              align: 'center',
              slotName: 'action',
            },
          ]
        },
        // 生产计划单明细表
        crmProductionPlanDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '单据类型',
              key: 'documentType',
              type: JVXETypes.select,
              options:[],
              dictCode:"document_type",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '订单编号',
              key: 'schedulingNumber',
               type: JVXETypes.input,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料编码',
              key: 'packageCode',
              type: JVXETypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料名称',
              key: 'packageName',
              type: JVXETypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '规格型号',
              key: 'noneSpec',
              type: JVXETypes.input,
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '单位',
              key: 'meUnit',
              type: JVXETypes.select,
              options:[],
              dictCode:"ji_unit",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '辅单位',
              key: 'auUnit',
              type: JVXETypes.select,
              options:[],
              dictCode:"zl_unit",
              disabled:true,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '订单数量',
              key: 'mainQuantity',
              type: JVXETypes.inputNumber,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
              statistics:['sum']
            },
            {
              title: '库存数量',
              key: 'quantity',
              type: JVXETypes.inputNumber,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
              statistics:['sum']
            },
            {
              title: '辅数量',
              key: 'auxiliaryQuantity',
              type: JVXETypes.inputNumber,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
              statistics:['sum']
            },
            {
              title: '已转计划数量',
              key: 'completedQuantity',
               type: JVXETypes.inputNumber,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
              statistics:['sum']
            },
            {
              title: '未转计划数量',
              key: 'unfinishedQuantity',
               type: JVXETypes.inputNumber,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
              statistics:['sum']
            },
            {
              title: '本次计划数量',
              key: 'planQuantity',
              type: JVXETypes.slot,
              slotName:'planQuantity',
              width:"200px",
            },
/*            {
              title: '宝洁订单号',
              key: 'pgCode',
              type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },*/
            {
              title: '交货日期',
              key: 'deliveryTime',
              type: JVXETypes.input,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '下单部门',
              key: 'orderSysOrgCode_dictText',
              type: JVXETypes.input,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '下单人',
              key: 'orderCreateBy_dictText',
               type: JVXETypes.input,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '下单日期',
              key: 'orderCreateTime',
              type: JVXETypes.date,
              width:"200px",
              disabled:true,
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/productionplan/crmProductionPlan/add",
          edit: "/productionplan/crmProductionPlan/edit",
          queryById: "/productionplan/crmProductionPlan/queryById",
          queryCrmTradeOrderGoodsByMainIds:"/review/crmTradeOrder/queryCrmTradeOrderGoodsByMainIds",
          crmProductionPlanFile: {
            list: '/productionplan/crmProductionPlan/queryCrmProductionPlanFileByMainId'
          },
          crmProductionPlanDetail: {
            list: '/productionplan/crmProductionPlan/queryCrmProductionPlanDetailByMainId'
          },
        },
        needSet:{
          flag:0,
          status:"",
          message:""
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      customFormData: {
        type: Object,
        default: () => {
          return {}
        },
        required: false,
      },
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      if (this.customFormData != null && this.customFormData.id) {
        this.model = this.customFormData
        this.editAfter() //现在子表内容需要
      }
    },
    methods: {
       handleOk() {
        console.log("来了哦")
        let message=""
        let flag=false
        console.log("this.crmProductionPlanDetailTable",this.crmProductionPlanDetailTable.dataSource)
        const resultList = this.crmProductionPlanDetailTable.dataSource
          .filter(item => item.orderId && item.packageCode)
          .map(item => ({
            [item.orderId]: item.packageCode  // 创建 { orderId: packageCode } 的对象
          }));
        console.log("map",resultList)
        let param={}
        param.salesType='1'
        param.map=resultList
        console.log("sdada",param)
         postAction("/productionplan/crmProductionPlan/selectFiles",param).then((res)=>{
          if (res.success){
            flag=res.result.flag
            console.log("ten",res.result)
            message=res.result.message
          }
           if (!flag){
             message=message.split(',').join('<br>')
             this.$alert(
               message,
               '配方更改未上传附件',
               {
                 dangerouslyUseHTMLString: true,  // 允许解析 HTML 标签如 <br>
                 confirmButtonText: '确定'
               }
             );
             throw new Error("配方更改未上传附件");
           }
        }).then(()=>{
           if(this.needSet.flag===0){
             this.handleComplete().then(()=>{
               if(this.needSet.status=="error"){
                 this.$message.error("物料不齐全");
                 throw new Error("物料不齐全");
               }
             })
           }
           if(this.needSet.status=="error"){
             this.$message.error("物料不齐全");
             throw new Error("物料不齐全");
           }
         }).then(()=>{/** 触发表单验证 */
           return this.getAllTable()
        }).then(tables => {
             /** 一次性验证主表和所有的次表 */
             return validateFormModelAndTables(this.$refs.form,this.model, tables)
           }).then(allValues => {
             /** 一次性验证一对一的所有子表 */
             return this.validateSubForm(allValues)
           }).then(allValues => {
             if (typeof this.classifyIntoFormData !== 'function') {
               throw this.throwNotFunction('classifyIntoFormData')
             }
             let formData = this.classifyIntoFormData(allValues)
             // 发起请求
             return this.request(formData)
           }).catch(e => {
             if (e.error === VALIDATE_FAILED) {
               // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
               this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
             } else {
               console.error(e)
             }
           })
      },
       handleComplete(){
         console.log("1111111111111", this.crmProductionPlanDetailTable.dataSource);

         // 返回 postAction 的 Promise
         postAction("/productionplan/crmProductionPlan/handleCompleteSet", this.crmProductionPlanDetailTable.dataSource)
           .then((res) => {
             console.log(res);
             if (res.result.status === 'ok') {
               this.$message.success("物料齐套，满足生产条件");
               console.log("222222222222222222222");
             } else if (res.result.status == 'error') {
               console.log("11111111111111111111111111111111111112", res.result.order);
               this.$alert(
                 res.result.order,
                 '物料数量不足提醒',
                 {
                   dangerouslyUseHTMLString: true,  // 允许解析 HTML 标签如 <br>
                   confirmButtonText: '确定'
                 }
               );
             }
             console.log("sdadadadadadadad",this.needSet)

             this.needSet.flag = 1;
             this.needSet.status = res.result.status;
             this.needSet.message = res.result.order;
             console.log("sdadadadadadadad",this.needSet)
             return res; // 可选：返回结果供外部使用
           })
           .catch((error) => {
             console.error("handleComplete 失败:", error);
             throw error; // 抛出错误，让外部 catch 捕获
           });
      },
      planQuantityInput(row){
        if(row.planQuantity>row.unfinishedQuantity){
          row.planQuantity = row.unfinishedQuantity
        }
      },
      getCode() {
        postAction('/sys/fillRule/executeRuleByCode/production_plan_code', {}).then((res) => {
          this.model.planCode = res.result
          this.$forceUpdate()
        })
      },
      /** 当点击新增按钮时调用此方法 */
      add(record) {
        console.log("addrecord===",record)
        this.model.salesType = '1'
        this.getCode()
        let ids = record.map(e=>e.id).join(',')
        if (typeof this.addBefore === 'function') this.addBefore()
        getAction(this.url.queryCrmTradeOrderGoodsByMainIds,{ids:ids}).then((res)=>{
          if(res.success){

            for (let i = 0; i < res.result.length; i++) {
              let filterElement = record.filter(o => o.id === res.result[i].orderId)[0];

              let assign = Object.assign({}, filterElement,res.result[i]);
              assign.quantity = assign.quantity==null?0:assign.quantity
              assign.completedQuantity = assign.completedQuantity==null?0:assign.completedQuantity
              assign.unfinishedQuantity =  (assign.mainQuantity - assign.completedQuantity).toFixed(3)
              assign.orderSysOrgCode = assign.sysOrgCode
              assign.orderSysOrgCode_dictText = assign.sysOrgCode_dictText
              assign.orderCreateBy = assign.createBy
              assign.orderCreateBy_dictText = assign.createBy_dictText
              assign.orderCreateTime = assign.createTime
              assign.createTime = null
              assign.createBy = null
              assign.sysOrgCode = null

              this.crmProductionPlanDetailTable.dataSource.push(assign)
            }
          }

        })
        this.edit(this.model)
      },
      handlePreviewReviewDesFiles(row) {
        if (row && row.files) {
          FilePreview(row.files)
        }
      },
      addBefore(){
        this.crmProductionPlanFileTable.dataSource=[]
        this.crmProductionPlanDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.crmProductionPlanFile.list, params, this.crmProductionPlanFileTable)
          this.requestSubTableData(this.url.crmProductionPlanDetail.list, params, this.crmProductionPlanDetailTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          crmProductionPlanFileList: allValues.tablesValue[0].tableData,
          crmProductionPlanDetailList: allValues.tablesValue[1].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>